/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.wonderly.output.log;

import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;
import org.wonderly.log.StreamFormatter;

/**
 * This class provides the default implementation for logging information about module
 * activities including errors as well as advisory information.  The standard java
 * {@link java.util.Logger} facilities are used by this default implementation.  If you
 * want to substitute log4j or something else into use for your installation, then you
 * can using a @{link ServiceProvider} that implements {@link LogProvider}.
 * @author gregg
 */
@ServiceProvider(service=LogProvider.class,position=10000)
public class LogProviderImpl implements LogProvider{
	private IOProvider io;
	private ConcurrentHashMap<String,Logger> map = new ConcurrentHashMap<String,Logger>();

	public LogProviderImpl() {
		io = IOProvider.getDefault();
	}

	public Logger getLogging(String name ) {
		return getLogging( name, new StreamFormatter() );
	}

	public Logger getLogging(String name, Formatter fmt ) {
		Logger log = Logger.getLogger( "thedesk."+name );
		final InputOutput iop = io.getIO( name, true );
		Handler h = new Handler() {
			@Override
			public void publish(LogRecord record) {
				String str = getFormatter().format( record );
				iop.getOut().print(str);
				flush();
			}

			@Override
			public void flush() {
				iop.getOut().flush();
			}

			@Override
			public void close() throws SecurityException {
				iop.getOut().close();
			}
		};
		h.setFormatter( fmt );
		log.addHandler(h);
		map.put( name, log );
		return log;
	}
}
